/**
 * 客户资料 - 主界面
 * 
 * @author PSI
 * @copyright 2015 - present
 * @license GPL v3
 */
PCL.define("PSI.SLN0001.Customer.MainForm", {
  extend: "PSI.AFX.Form.MainForm",
  border: 0,

  config: {
    pAddCategory: null,
    pEditCategory: null,
    pDeleteCategory: null,
    pAddCustomer: null,
    pEditCustomer: null,
    pDeleteCustomer: null,
    pImportCustomer: null
  },

  /**
   * 初始化组件
   * 
   * @override
   */
  initComponent() {
    const me = this;

    PCL.apply(me, {
      layout: "border",
      items: [{
        tbar: me.getToolbarCmp(),
        id: me.buildId(me, "panelQueryCmp"),
        region: "north",
        height: 95,
        border: 0,
        collapsible: true,
        collapseMode: "mini",
        header: false,
        layout: {
          type: "table",
          columns: 6
        },
        bodyCls: "PSI-Query-Panel",
        items: me.getQueryCmp()
      }, {
        region: "center",
        layout: "border",
        border: 0,
        ...PSI.Const.BODY_PADDING,
        items: [{
          region: "center",
          xtype: "panel",
          layout: "border",
          border: 0,
          items: [{
            region: "north",
            border: 1,
            height: 30,
            /**
             * 这个panel只是为了使用其tbar展示信息
             * 这么做的原因是：MainGrid的column中用了lock属性后，
             * 导致页面在1920*1080分辨率（125%的放大率）下显示不正常。
             * 这应该是PCL的bug，但是目前尚未找到如何修正，所以采用这种方式迂回处理一下。
             */
            xtype: "panel",
            margin: 0,
            cls: "PSI-LC",
            tbar: [" ", {
              xtype: "displayfield", value: "客户列表",
              id: me.buildId(me, "dfMainGridInfo")
            }, "->",
              {
                id: "pagingToolbar",
                border: 0,
                xtype: "pagingtoolbar",
                store: me.getMainGrid().getStore(),
              }, "-", {
                xtype: "displayfield",
                fieldStyle: "font-size:13px",
                value: "每页显示"
              }, {
                id: "comboCountPerPage",
                xtype: "combobox",
                editable: false,
                width: 60,
                store: PCL.create("PCL.data.ArrayStore", {
                  fields: ["text"],
                  data: [["20"], ["50"], ["100"], ["300"],
                  ["1000"]]
                }),
                value: 20,
                listeners: {
                  change: {
                    fn() {
                      const store = me.getMainGrid().getStore();
                      store.pageSize = PCL.getCmp("comboCountPerPage").getValue();
                      store.currentPage = 1;
                      PCL.getCmp("pagingToolbar").doRefresh();
                    },
                    scope: me
                  }
                }
              }, {
                xtype: "displayfield",
                fieldStyle: "font-size:13px",
                value: "条记录"
              }]
          }, {
            region: "center",
            layout: "fit",
            border: 0,
            items: me.getMainGrid()
          }]
        }, {
          id: "panelCategory",
          xtype: "panel",
          region: "west",
          layout: "fit",
          width: 430,
          split: true,
          collapsible: true,
          header: false,
          border: 0,
          items: [me.getCategoryGrid()]
        }]
      }]
    });

    me.callParent(arguments);

    me.categoryGrid = me.getCategoryGrid();
    me.customerGrid = me.getMainGrid();

    me._dfMainGridInfo = PCL.getCmp(me.buildId(me, "dfMainGridInfo"));

    // AFX
    me.__editorList = [
      PCL.getCmp(me.buildId(me, "editQueryCode")),
      PCL.getCmp(me.buildId(me, "editQueryName")),
      PCL.getCmp(me.buildId(me, "editQueryAddress")),
      PCL.getCmp(me.buildId(me, "editQueryContact")),
      PCL.getCmp(me.buildId(me, "editQueryMobile")),
      PCL.getCmp(me.buildId(me, "editQueryTel")),
      PCL.getCmp(me.buildId(me, "editQueryQQ"))
    ];

    me._keyMapMain = PCL.create("PCL.util.KeyMap", PCL.getBody(), [{
      key: "N",
      ctrl: false,
      shift: false,
      alt: true,
      fn() {
        if (PSI.Const.msgBoxShowing) {
          return;
        }

        // 判断权限
        if (me.getPAddCustomer() != "1") {
          return;
        }

        me._onAddCustomer.apply(me, []);
      },
      scope: me
    }, {
      key: "Q",
      ctrl: false,
      shift: false,
      alt: true,
      fn() {
        if (PSI.Const.msgBoxShowing) {
          return;
        }
        PCL.getCmp(me.buildId(me, "editQueryCode"))?.focus();
      },
      scope: me
    }, {
      key: "H",
      ctrl: false,
      shift: false,
      alt: true,
      fn() {
        if (PSI.Const.msgBoxShowing) {
          return;
        }

        const panel = PCL.getCmp(me.buildId(me, "panelQueryCmp"));
        if (panel.getCollapsed()) {
          panel.expand();
        } else {
          panel.collapse();
        };
      },
      scope: me
    },
    ]);

    me.freshCategoryGrid();
  },

  /**
   * @private
   */
  getToolbarCmp() {
    const me = this;

    const result = [];
    const list = [];
    if (me.getPAddCategory() == "1") {
      list.push({
        text: "新建客户分类",
        ...PSI.Const.BTN_STYLE,
        handler: me._onAddCategory,
        scope: me
      });
    }
    if (me.getPEditCategory() == "1") {
      list.push({
        text: "编辑客户分类",
        ...PSI.Const.BTN_STYLE,
        handler: me._onEditCategory,
        scope: me
      });
    }
    if (me.getPDeleteCategory() == "1") {
      list.push({
        text: "删除客户分类",
        ...PSI.Const.BTN_STYLE,
        handler: me._onDeleteCategory,
        scope: me
      });
    }
    if (list.length > 0) {
      result.push({
        text: "客户分类",
        iconCls: "PSI-tb-new",
        ...PSI.Const.BTN_STYLE,
        menu: list
      });
    }

    let sep = list.length > 0;
    if (me.getPAddCustomer() == "1") {
      if (sep) {
        result.push("-");
        sep = false;
      }

      result.push({
        iconCls: "PSI-tb-new-entity",
        text: "新建客户 <span class='PSI-shortcut-DS'>Alt + N</span>",
        tooltip: me.buildTooltip("快捷键：Alt + N"),
        ...PSI.Const.BTN_STYLE,
        handler: me._onAddCustomer,
        scope: me
      });
    }

    if (me.getPImportCustomer() == "1") {
      if (sep) {
        result.push("-");
        sep = false;
      }

      result.push({
        text: "导入客户",
        ...PSI.Const.BTN_STYLE,
        handler: me._onImportCustomer,
        scope: me
      });
    }

    if (me.getPEditCustomer() == "1") {
      if (sep) {
        result.push("-");
        sep = false;
      }

      result.push({
        text: "编辑客户",
        ...PSI.Const.BTN_STYLE,
        handler: me._onEditCustomer,
        scope: me
      });
    }

    if (me.getPDeleteCustomer() == "1") {
      if (sep) {
        result.push("-");
        sep = false;
      }

      result.push({
        text: "删除客户",
        ...PSI.Const.BTN_STYLE,
        handler: me._onDeleteCustomer,
        scope: me
      });
    }

    sep = result.length > 0;
    if (sep) {
      result.push("-");
      sep = false;
    }

    result.push({
      iconCls: "PSI-tb-help",
      text: "指南",
      ...PSI.Const.BTN_STYLE,
      handler() {
        me.focus();
        window.open(me.URL("Home/Help/index?t=customer"));
      }
    }, "-", {
      iconCls: "PSI-tb-close",
      text: "关闭",
      ...PSI.Const.BTN_STYLE,
      handler() {
        me.focus();
        me.closeWindow();
      }
    }, {
      // 空容器，只是为了撑高工具栏
      xtype: "container", height: 28,
      items: []
    });

    return result.concat(me.getShortcutCmp());
  },

  /**
   * 快捷访问
   * 
   * @private
   */
  getShortcutCmp() {
    return ["->",
      {
        cls: "PSI-Shortcut-Cmp",
        labelWidth: 0,
        emptyText: "快捷访问",
        xtype: "psi_mainmenushortcutfield",
        width: 90
      }
    ];
  },

  /**
   * @private
   */
  getQueryCmp() {
    const me = this;

    return [{
      xtype: "container",
      height: 26,
      html: `<h2 style='margin-left:20px;margin-top:18px;color:#595959;display:inline-block'>客户资料</h2>
              &nbsp;&nbsp;<span style='color:#8c8c8c'>主数据</span>
              <div style='float:right;display:inline-block;margin:10px 0px 0px 20px;border-left:1px solid #e5e6e8;height:40px'>&nbsp;</div>
              `
    }, {
      id: me.buildId(me, "editQueryCode"),
      labelWidth: 105,
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "客户编码 <span class='PSI-shortcut-DS'>Alt + Q</span>",
      width: 250,
      margin: "5, 0, 0, 0",
      xtype: "textfield",
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      }
    }, {
      id: me.buildId(me, "editQueryName"),
      labelWidth: 60,
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "客户名称",
      margin: "5, 0, 0, 0",
      xtype: "textfield",
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      }
    }, {
      id: me.buildId(me, "editQueryAddress"),
      labelWidth: 60,
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "地址",
      margin: "5, 0, 0, 0",
      xtype: "textfield",
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      }
    }, {
      id: me.buildId(me, "editQueryContact"),
      labelWidth: 60,
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "联系人",
      margin: "5, 0, 0, 0",
      xtype: "textfield",
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      }
    }, {
      id: me.buildId(me, "editQueryMobile"),
      labelWidth: 60,
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "手机",
      margin: "5, 0, 0, 0",
      xtype: "textfield",
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      }
    }, { xtype: "container" }, {
      id: me.buildId(me, "editQueryTel"),
      labelWidth: 70,
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "固话",
      width: 250,
      margin: "5, 0, 0, 0",
      xtype: "textfield",
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      }
    }, {
      id: me.buildId(me, "editQueryQQ"),
      labelWidth: 60,
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "QQ",
      margin: "5, 0, 0, 0",
      xtype: "textfield",
      listeners: {
        specialkey: {
          fn: me.__onLastEditSpecialKey,
          scope: me
        }
      }
    }, {
      id: me.buildId(me, "editQueryRecordStatus"),
      xtype: "combo",
      queryMode: "local",
      editable: false,
      valueField: "id",
      labelWidth: 60,
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "状态",
      margin: "5, 0, 0, 0",
      store: PCL.create("PCL.data.ArrayStore", {
        fields: ["id", "text"],
        data: [[-1, "全部"], [1000, "启用"], [0, "停用"]]
      }),
      value: -1
    }, {
      xtype: "container",
      items: [{
        xtype: "button",
        text: "查询",
        cls: "PSI-Query-btn1",
        width: 100,
        height: 26,
        margin: "5, 0, 0, 20",
        handler: me._onQuery,
        scope: me
      }, {
        xtype: "button",
        text: "清空查询条件",
        cls: "PSI-Query-btn2",
        width: 100,
        height: 26,
        margin: "5, 0, 0, 15",
        handler: me._onClearQuery,
        scope: me
      }]
    }, {
      xtype: "container",
      items: [{
        xtype: "button",
        text: "隐藏工具栏 <span class='PSI-shortcut-DS'>Alt + H</span>",
        cls: "PSI-Query-btn3",
        width: 140,
        height: 26,
        iconCls: "PSI-button-hide",
        margin: "5 0 0 20",
        handler() {
          PCL.getCmp(me.buildId(me, "panelQueryCmp")).collapse();
        },
        scope: me
      }]
    }];
  },

  /**
   * @private
   */
  getCategoryGrid() {
    const me = this;

    if (me._categoryGrid) {
      return me._categoryGrid;
    }

    const modelName = me.buildModelName(me, "CustomerCategory");

    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id", "code", "name", {
        name: "cnt",
        type: "int"
      }, "priceSystem"]
    });

    me._categoryGrid = PCL.create("PCL.grid.Panel", {
      cls: "PSI-FC",
      viewConfig: {
        enableTextSelection: true
      },
      header: {
        height: 30,
        title: me.formatGridHeaderTitle(me.toTitleKeyWord("客户分类")),
      },
      tools: [{
        type: "close",
        handler() {
          PCL.getCmp("panelCategory").collapse();
        }
      }],
      features: [{
        ftype: "summary"
      }],
      columnLines: true,
      columns: [{
        header: "类别编码",
        dataIndex: "code",
        width: 80,
        menuDisabled: true,
        sortable: false
      }, {
        header: "类别",
        dataIndex: "name",
        width: 160,
        menuDisabled: true,
        sortable: false,
        summaryRenderer() {
          return "客户数合计";
        }
      }, {
        header: "价格体系",
        dataIndex: "priceSystem",
        width: 80,
        menuDisabled: true,
        sortable: false
      }, {
        header: "客户数",
        dataIndex: "cnt",
        width: 80,
        menuDisabled: true,
        sortable: false,
        summaryType: "sum",
        align: "right"
      }],
      store: PCL.create("PCL.data.Store", {
        model: modelName,
        autoLoad: false,
        data: []
      }),
      listeners: {
        select: {
          fn: me._onCategoryGridSelect,
          scope: me
        },
        itemdblclick: {
          fn: me._onEditCategory,
          scope: me
        }
      }
    });

    return me._categoryGrid;
  },

  /**
   * @private
   */
  getMainGrid() {
    const me = this;
    if (me._mainGrid) {
      return me._mainGrid;
    }

    const modelName = me.buildModelName(me, "CustomerModel");

    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id", "code", "name", "contact01", "tel01",
        "mobile01", "qq01", "contact02", "tel02",
        "mobile02", "qq02", "categoryId",
        "initReceivables", "initReceivablesDT", "address",
        "addressReceipt", "bankName", "bankAccount", "tax",
        "fax", "note", "dataOrg", "warehouseName",
        "recordStatus"]
    });

    const store = PCL.create("PCL.data.Store", {
      autoLoad: false,
      model: modelName,
      data: [],
      pageSize: 20,
      proxy: {
        type: "ajax",
        actionMethods: {
          read: "POST"
        },
        url: me.URL("SLN0001/Customer/customerList"),
        reader: {
          root: 'customerList',
          totalProperty: 'totalCount'
        }
      },
      listeners: {
        beforeload: {
          fn() {
            store.proxy.extraParams = me.getQueryParam();
          },
          scope: me
        },
        load: {
          fn(e, records, successful) {
            if (successful) {
              me.refreshCategoryCount();
              me.gotoCustomerGridRecord(me._lastId);
            }
          },
          scope: me
        }
      }
    });

    me._mainGrid = PCL.create("PCL.grid.Panel", {
      cls: "PSI-LC",
      viewConfig: {
        enableTextSelection: true
      },
      columnLines: true,
      columns: {
        defaults: {
          menuDisabled: true,
          sortable: false
        },
        items: [PCL.create("PCL.grid.RowNumberer", {
          text: "#",
          width: 40
        }), {
          header: "客户编码",
          dataIndex: "code",
          locked: true,
          renderer(value, metaData, record) {
            if (parseInt(record.get("recordStatus")) == 1000) {
              return value;
            } else {
              return `<span class="PSI-record-disabled">${value}</span>`;
            }
          }
        }, {
          header: "客户名称",
          dataIndex: "name",
          locked: true,
          width: 300,
          renderer(value, metaData, record) {
            if (parseInt(record.get("recordStatus")) == 1000) {
              return value;
            } else {
              return `<span class="PSI-record-disabled">${value}</span>`;
            }
          }
        }, {
          header: "地址",
          dataIndex: "address",
          width: 300
        }, {
          header: "联系人",
          dataIndex: "contact01"
        }, {
          header: "手机",
          dataIndex: "mobile01"
        }, {
          header: "固话",
          dataIndex: "tel01"
        }, {
          header: "QQ",
          dataIndex: "qq01"
        }, {
          header: "备用联系人",
          dataIndex: "contact02"
        }, {
          header: "备用联系人手机",
          dataIndex: "mobile02",
          width: 150
        }, {
          header: "备用联系人固话",
          dataIndex: "tel02",
          width: 150
        }, {
          header: "备用联系人QQ",
          dataIndex: "qq02",
          width: 150
        }, {
          header: "收货地址",
          dataIndex: "addressReceipt",
          width: 300
        }, {
          header: "开户行",
          dataIndex: "bankName"
        }, {
          header: "开户行账号",
          dataIndex: "bankAccount"
        }, {
          header: "社会统一信用代码",
          dataIndex: "tax",
          width: 150,
        }, {
          header: "传真",
          dataIndex: "fax"
        }, {
          header: "应收期初余额",
          dataIndex: "initReceivables",
          align: "right",
          xtype: "numbercolumn"
        }, {
          header: "应收期初余额日期",
          dataIndex: "initReceivablesDT",
          width: 150
        }, {
          header: "销售出库仓库",
          dataIndex: "warehouseName",
          width: 200
        }, {
          header: "备注",
          dataIndex: "note",
          width: 400
        }, {
          header: "数据域",
          dataIndex: "dataOrg"
        }, {
          header: "状态",
          dataIndex: "recordStatus",
          renderer(value) {
            if (parseInt(value) == 1000) {
              return "启用";
            } else {
              return "<span style='color:red'>停用</span>";
            }
          }
        }]
      },
      store,
      listeners: {
        itemdblclick: {
          fn: me._onEditCustomer,
          scope: me
        }
      }
    });

    return me._mainGrid;
  },

  /**
   * 新建客户分类
   * 
   * @private
   */
  _onAddCategory() {
    const me = this;

    const form = PCL.create("PSI.SLN0001.Customer.CategoryEditForm", {
      parentForm: me,
      renderTo: PSI.Const.RENDER_TO(),
    });

    form.show();
  },

  /**
   * 编辑客户分类
   * 
   * @private
   */
  _onEditCategory() {
    const me = this;
    if (me.getPEditCategory() == "0") {
      return;
    }

    const item = me.getCategoryGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("请选择要编辑的客户分类");
      return;
    }

    const category = item[0];

    const form = PCL.create("PSI.SLN0001.Customer.CategoryEditForm", {
      parentForm: me,
      entity: category,
      renderTo: PSI.Const.RENDER_TO(),
    });

    form.show();
  },

  /**
   * 删除客户分类
   * 
   * @private
   */
  _onDeleteCategory() {
    const me = this;
    const item = me.categoryGrid.getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("请选择要删除的客户分类");
      return;
    }

    const category = item[0];

    const store = me.getCategoryGrid().getStore();
    let index = store.findExact("id", category.get("id"));
    index--;
    let preIndex = null;
    const preItem = store.getAt(index);
    if (preItem) {
      preIndex = preItem.get("id");
    }

    const info = `请确认是否删除客户分类: <span style='color:red'>${category.get("name")}</span> ？`;

    const funcConfirm = () => {
      const el = PCL.getBody();
      el.mask("正在删除中...");

      const r = {
        url: me.URL("SLN0001/Customer/deleteCategory"),
        params: {
          id: category.get("id")
        },
        callback(options, success, response) {
          el.unmask();

          if (success) {
            const data = me.decodeJSON(response.responseText);
            if (data.success) {
              me.tip("成功完成删除操作", true);
              me.freshCategoryGrid(preIndex);
            } else {
              me.showInfo(data.msg);
            }
          } else {
            me.showInfo("网络错误");
          }
        }
      };

      me.ajax(r);
    };

    me.confirm(info, funcConfirm);
  },

  /**
   * 刷新客户分类Grid
   * 
   * @private
   */
  freshCategoryGrid(id) {
    const me = this;
    const grid = me.getCategoryGrid();
    const el = grid.getEl() || PCL.getBody();
    el.mask(PSI.Const.LOADING);
    me.ajax({
      url: me.URL("SLN0001/Customer/categoryList"),
      params: me.getQueryParam(),
      callback(options, success, response) {
        const store = grid.getStore();

        store.removeAll();

        if (success) {
          const data = me.decodeJSON(response.responseText);
          store.add(data);

          if (store.getCount() > 0) {
            if (id) {
              const r = store.findExact("id", id);
              if (r != -1) {
                grid.getSelectionModel().select(r);
              }
            } else {
              grid.getSelectionModel().select(0);
            }
          }
        }

        el.unmask();
      }
    });
  },

  /**
   * 刷新客户资料Grid
   * 
   * @private
   */
  freshCustomerGrid(id) {
    const me = this;

    const item = me.getCategoryGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      const grid = me.getMainGrid();
      grid.setTitle(me.formatGridHeaderTitle("客户列表"));
      return;
    }

    const category = item[0];

    const info = `<span class='PSI-title-keyword'>${category.get("name")}</span> - 客户列表`;
    me._dfMainGridInfo.setValue(info);

    me._lastId = id;
    PCL.getCmp("pagingToolbar").doRefresh()
  },

  /**
   * @private
   */
  _onCategoryGridSelect() {
    const me = this;
    me.getMainGrid().getStore().currentPage = 1;
    me.freshCustomerGrid();
  },

  /**
   * 新增客户资料
   * 
   * @private
   */
  _onAddCustomer() {
    const me = this;

    if (me.getCategoryGrid().getStore().getCount() == 0) {
      me.showInfo("没有客户分类，请先新增客户分类");
      return;
    }

    const form = PCL.create("PSI.SLN0001.Customer.CustomerEditForm", {
      parentForm: me,
      renderTo: PSI.Const.RENDER_TO(),
    });

    form.show();
  },

  /**
   * 导入客户资料
   * 
   * @private
   */
  _onImportCustomer() {
    const me = this;

    const form = PCL.create("PSI.SLN0001.Customer.CustomerImportForm", {
      parentForm: me,
      renderTo: PSI.Const.RENDER_TO(),
    });

    form.show();
  },

  /**
   * 编辑客户资料
   * 
   * @private
   */
  _onEditCustomer() {
    const me = this;
    if (me.getPEditCustomer() == "0") {
      return;
    }

    let item = me.getCategoryGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("没有选择客户分类");
      return;
    }
    const category = item[0];

    item = me.getMainGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("请选择要编辑的客户");
      return;
    }

    const customer = item[0];
    customer.set("categoryId", category.get("id"));
    const form = PCL.create("PSI.SLN0001.Customer.CustomerEditForm", {
      parentForm: me,
      entity: customer,
      renderTo: PSI.Const.RENDER_TO(),
    });

    form.show();
  },

  /**
   * 删除客户资料
   * 
   * @private
   */
  _onDeleteCustomer() {
    const me = this;
    const item = me.getMainGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("请选择要删除的客户");
      return;
    }

    const customer = item[0];

    const store = me.getMainGrid().getStore();
    let index = store.findExact("id", customer.get("id"));
    index--;
    let preIndex = null;
    const preItem = store.getAt(index);
    if (preItem) {
      preIndex = preItem.get("id");
    }

    const info = `请确认是否删除客户: <span style='color:red'>${customer.get("name")}</span> ？`;

    const funcConfirm = () => {
      const el = PCL.getBody();
      el.mask("正在删除中...");

      const r = {
        url: me.URL("SLN0001/Customer/deleteCustomer"),
        params: {
          id: customer.get("id")
        },
        callback(options, success, response) {
          el.unmask();

          if (success) {
            const data = me.decodeJSON(response.responseText);
            if (data.success) {
              me.tip("成功完成删除操作", true);
              me.freshCustomerGrid(preIndex);
            } else {
              me.showInfo(data.msg);
            }
          }
        }

      };

      me.ajax(r);
    };

    me.confirm(info, funcConfirm);
  },

  /**
   * @private
   */
  gotoCustomerGridRecord(id) {
    const me = this;
    const grid = me.getMainGrid();
    const store = grid.getStore();
    if (id) {
      const r = store.findExact("id", id);
      if (r != -1) {
        grid.getSelectionModel().select(r);
        grid.getSelectionModel().setLastFocused(store.getAt(r));
      } else {
        grid.getSelectionModel().select(0);
      }
    } else {
      grid.getSelectionModel().select(0);
    }
  },

  /**
   * @private
   */
  refreshCategoryCount() {
    const me = this;
    const item = me.getCategoryGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      return;
    }

    const category = item[0];
    category.set("cnt", me.getMainGrid().getStore().getTotalCount());
    me.getCategoryGrid().getStore().commitChanges();
  },

  /**
   * @private
   */
  getQueryParam() {
    const me = this;
    const item = me.getCategoryGrid().getSelectionModel().getSelection();
    let categoryId;
    if (item == null || item.length != 1) {
      categoryId = null;
    } else {
      categoryId = item[0].get("id");
    }

    const result = {
      categoryId: categoryId
    };

    const code = PCL.getCmp(me.buildId(me, "editQueryCode")).getValue();
    if (code) {
      result.code = code;
    }

    const address = PCL.getCmp(me.buildId(me, "editQueryAddress")).getValue();
    if (address) {
      result.address = address;
    }

    const name = PCL.getCmp(me.buildId(me, "editQueryName")).getValue();
    if (name) {
      result.name = name;
    }

    const contact = PCL.getCmp(me.buildId(me, "editQueryContact")).getValue();
    if (contact) {
      result.contact = contact;
    }

    const mobile = PCL.getCmp(me.buildId(me, "editQueryMobile")).getValue();
    if (mobile) {
      result.mobile = mobile;
    }

    const tel = PCL.getCmp(me.buildId(me, "editQueryTel")).getValue();
    if (tel) {
      result.tel = tel;
    }

    const qq = PCL.getCmp(me.buildId(me, "editQueryQQ")).getValue();
    if (qq) {
      result.qq = qq;
    }

    result.recordStatus = PCL.getCmp(me.buildId(me, "editQueryRecordStatus")).getValue();

    return result;
  },

  /**
   * 查询
   * 
   * @private
   */
  _onQuery() {
    const me = this;

    me.getMainGrid().getStore().removeAll();
    me.freshCategoryGrid();
  },

  /**
   * 清除查询条件
   * 
   * @private
   */
  _onClearQuery() {
    const me = this;

    PCL.getCmp(me.buildId(me, "editQueryCode")).setValue("");
    PCL.getCmp(me.buildId(me, "editQueryName")).setValue("");
    PCL.getCmp(me.buildId(me, "editQueryAddress")).setValue("");
    PCL.getCmp(me.buildId(me, "editQueryContact")).setValue("");
    PCL.getCmp(me.buildId(me, "editQueryMobile")).setValue("");
    PCL.getCmp(me.buildId(me, "editQueryTel")).setValue("");
    PCL.getCmp(me.buildId(me, "editQueryQQ")).setValue("");
    PCL.getCmp(me.buildId(me, "editQueryRecordStatus")).setValue(-1);

    me._onQuery();
  }
});
